using NETCore.Encrypt;
using zhwy.saas.api.Entity.Sys;
using zhwy.saas.api.Extensions.Enum;
using zhwy.saas.api.Extensions.Log;
using zhwy.saas.api.Models.Sys.Users;
using zhwy.saas.api.Repository;
using zhwy.saas.api.Services.Sinterface.Sys;

namespace zhwy.saas.api.Services.Sys
{
    /// <summary>
    /// 系统用户服务实现
    /// </summary>
    public class SysUserService : BaseService<UsersEntity>, ISysUserService
    {
        private readonly IConfiguration _config;

        private readonly ISysUserRoleService _userRoleService;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="repository">用户仓储接口</param>
        /// <param name="logger">日志服务</param>
        public SysUserService(IBaseRepository<UsersEntity> repository,
            IConfiguration config,
            ISysUserRoleService userRoleService,
            ILogExt logger)
            : base(repository, logger)
        {
            _config = config;
            _userRoleService = userRoleService;
        }

        /// <summary>
        /// 修改用户密码
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="newPassword">新密码</param>
        /// <returns>是否修改成功</returns>
        public async Task<bool> ChangePasswordAsync(long userId, string newPassword)
        {
            var user = await _repository.GetByIdAsync(userId);
            if (user == null)
                return false;

            // TODO: 密码加密处理
            user.Password = newPassword;
            return await _repository.UpdateAsync(user);
        }

        /// <summary>
        /// 检查用户帐号是否存在
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public async Task<bool> CheckUserNameExists(string username)
        {
            var user = await _repository.DbContext.Queryable<UsersEntity>()
               .Where(x => x.Username == username.Trim())
               .FirstAsync();
            return user != null ? true : false;
        }

        /// <summary>
        /// 租户添加账户信息
        /// </summary>
        /// <param name="tenantsEntity">租户信息</param>
        /// <param name="Password"></param>
        /// <param name="UserName"></param>
        /// <returns></returns>
        public async Task<bool> CreateTenantSysUserAsync(TenantsEntity tenantsEntity, string UserName, string Password)
        {
            var res = false;
            var password = EncryptProvider.Md5(Password + _config.GetConnectionString("passWordSecret"));
            var user = new UsersEntity()
            {
                Createtime = DateTime.Now,
                Createuserid = tenantsEntity.Createuserid,
                Password = password,
                Status = (int)EnumHelper.UsersStatus.use,
                Tenant_id = tenantsEntity.Id,
                Updatetime = DateTime.Now,
                Updateuserid = tenantsEntity.Updateuserid,
                Username = UserName,
                UserType = (int)EnumHelper.UserType.tenantadmin,
            };
            var userRes = await _repository.AddEntityAsync(user);
            if (userRes.Id > 0)
            {
                res = await _userRoleService.AddTeanantRoleAsync(userRes.Id);
            }
            return res;
        }

        /// <summary>
        /// 获取租户管理员账户信息
        /// </summary>
        /// <param name="tenant_id"></param>
        /// <returns></returns>
        public async Task<GetTenantAdminUserInfoRes> GetTenantAdminUserInfo(long tenant_id)
        {
            var user = await _repository.DbContext.Queryable<UsersEntity>()
                .Where(i => i.Tenant_id == tenant_id)
                .Where(i => i.UserType == (int)EnumHelper.UserType.tenantadmin)
                .FirstAsync();
            if (user != null)
            {
                return new GetTenantAdminUserInfoRes()
                {
                    Id = user.Id,
                    Username = user.Username,
                    UserType = user.UserType,
                };
            }
            return new GetTenantAdminUserInfoRes();
        }

        /// <summary>
        /// 更新用户状态
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="status">新状态</param>
        /// <returns>是否更新成功</returns>
        public async Task<bool> UpdateStatusAsync(long userId, int status)
        {
            var user = await _repository.GetByIdAsync(userId);
            if (user == null)
                return false;

            user.Status = status;
            return await _repository.UpdateAsync(user);
        }

    }
}